package com.mo.service.impl;

import com.mo.common.Result;
import com.mo.entity.User;
import com.mo.security.entity.LoginUser;
import com.mo.security.utils.JWTConstant;
import com.mo.security.utils.JwtUtils;
import com.mo.service.LoginService;
import com.mo.service.RedisService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisService redisService;

    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticated = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticated.getPrincipal();

        if (Objects.isNull(loginUser)) {
            return Result.error("用户名或密码有误", HttpServletResponse.SC_BAD_REQUEST);
        }

        String userId = loginUser.getUser().getId().toString();
        String username = loginUser.getUser().getUsername();

        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("loginTime", System.currentTimeMillis());

        String token = jwtUtils.generateToken(userId, claims);

        // 使用redis在这里设置登录信息,下面的示例为10分钟有效期
        redisService.setObject(JWTConstant.JWT_REDIS_PREFIX_USER + userId, loginUser, 60L, TimeUnit.MINUTES);

        return Result.success("登录成功", token);
    }
}
